<template>
  <!-- 合同填报 -->
  <div class="disf flex1 h0" v-loading="loading">
    <el-card class="mr10" shadow="never" header="内容填报">
      <el-scrollbar always>
        <ol class="fill-list">
          <li v-for="(item, index) in itemList" :key="item.key">
            {{ item.key }}：
            <el-input placeholder="请输入" v-model="item.value"></el-input>
          </li>
        </ol>
      </el-scrollbar>
    </el-card>

    <el-card class="flex1" shadow="never">
      <template #header>
        合同模板
        <el-button type="primary" size="small" class="ml15" @click="showChooseWindow">
          模板导入
        </el-button>
      </template>
      <WangEditor class="h" type="contract" v-model="editorVal" />
    </el-card>

    <!-- 模板弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="800px"
      @close="closeChooseWindow"
    >
      <ContractTempSelector ref="tempSelRef" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="chooseChooselDone">确 定</el-button>
          <el-button @click="closeChooseWindow">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import ContractAPI from "@/api/flow/contract.api";
import { parseCustomField } from "@/components/WangEditor/DisabledHtml";
import WangEditor from "@/components/WangEditor/index.vue";
import ContractTempSelector from "@/views/flow/contractTemp/ContractTempSelector.vue";
import { toMap } from "@/utils";

// 接收父组件
const props = defineProps<{
  id?: string;
}>();
const emits = defineEmits<{
  (e: "next"): void;
}>();

const loading = ref(false);
const editorVal = ref(""); // 富文本html
const itemList = ref<{ key: string; value: string }[]>([]); // 填报项列表
const itemValues = ref<{ [key: string]: string }>({}); // 填报项值

const dialog = reactive({
  title: "合同模板导入",
  visible: false,
});

const tempSelRef = ref();

onMounted(() => {
  loadContractDetail(props.id);
});

const loadContractDetail = async (id?: string) => {
  if (!id || id === "0") {
    return;
  }
  await ContractAPI.getFormData(id).then((data) => {
    itemValues.value = data.params ? JSON.parse(data.params) : {};
    editorVal.value = data.content || "";
  });
};

/**
 * 监听分割填报项
 */
watch(
  () => editorVal.value,
  (newVal) => {
    if (!newVal) return;
    // 获取自定义字段
    const customFields = parseCustomField(newVal);

    // 合并原值
    itemList.value = customFields.map((field) => ({
      key: field,
      value: itemValues.value[field] || "",
    }));
    itemValues.value = toMap(itemList.value, "key", "value") || {};
  }
);

/*
 * 弹窗：选择合同模板
 */
function showChooseWindow() {
  dialog.visible = true;
  nextTick(() => {
    tempSelRef.value.handleQuery();
  });
}

function closeChooseWindow() {
  dialog.visible = false;
}

const chooseChooselDone = async () => {
  ElMessageBox.confirm("模板导入后将覆盖原文本，确认导入?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    try {
      let choosed = tempSelRef.value.getChecked();
      if (!choosed) return;
      editorVal.value = choosed.content;
    } catch (error) {
      ElMessage.error("导入模板失败");
      console.error("导入模板失败", error);
    } finally {
      dialog.visible = false;
    }
  });
};

/**
 * 提交表单
 */
const handleSubmit = () => {
  if (!editorVal.value) {
    ElMessage.error("请选择合同模板，并填写合同内容");
    return;
  }
  if (!props.id) {
    ElMessage.error("合同id无效，请返回上一步");
    return;
  }
  loading.value = true;
  // 处理数据
  const pairMap: { [key: string]: string } = {};
  itemList.value.forEach(({ key, value }) => {
    pairMap[key] = value;
  });
  const editContent = editorVal.value.replaceAll(/\<br\>/g, "<br/>");
  const formData = {
    id: props.id,
    content: editContent,
    pairMap,
  };
  ContractAPI.fullContract(formData)
    .then(() => {
      ElMessage.success("保存合同成功");
      emits("next");
    })
    .finally(() => (loading.value = false));
};

defineExpose({
  handleSubmit,
});
</script>

<style lang="scss" scoped>
:deep(.el-card__body) {
  height: calc(100% - 61px);
  .el-scrollbar {
    margin-right: -10px;
    padding-right: 10px;
  }
}
.fill-list {
  width: 200px;
  font-size: small;
  li {
    margin-bottom: 10px;
  }
}
</style>
